import * as BackgroundFetch from 'expo-background-fetch';
import * as TaskManager from 'expo-task-manager';
import AsyncStorage from '@react-native-async-storage/async-storage';
import notifee, { AndroidImportance, EventType } from '@notifee/react-native';
import { AppState, Platform } from 'react-native';

const BACKGROUND_TIMER_TASK = 'BACKGROUND_TIMER_TASK';
let intervalId: NodeJS.Timeout | null = null;
let startTime: number | null = null;
let accumulatedTime: number = 0;

interface TimerState {
  isRunning: boolean;
  startTime: number | null;
  accumulatedTime: number;
  taskTitle: string;
}

// 创建通知频道
async function createNotificationChannel() {
  if (Platform.OS === 'android') {
    await notifee.createChannel({
      id: 'timer',
      name: '计时器',
      lights: false,
      vibration: false,
      importance: AndroidImportance.LOW,
    });
  }
}

// 更新通知
async function updateNotification(taskTitle: string, totalSeconds: number) {
  const hours = Math.floor(totalSeconds / 3600);
  const minutes = Math.floor((totalSeconds % 3600) / 60);
  const seconds = totalSeconds % 60;
  const timeString = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;

  if (Platform.OS === 'android') {
    await notifee.displayNotification({
      id: 'timer',
      title: '时间追踪',
      body: `${taskTitle}: ${timeString}`,
      android: {
        channelId: 'timer',
        asForegroundService: true,
        ongoing: true,
        autoCancel: false,
        importance: AndroidImportance.LOW,
        pressAction: {
          id: 'default',
        },
        actions: [
          {
            title: '停止',
            pressAction: {
              id: 'stop',
            },
          },
        ],
      },
    });
  }
}

// 保存计时器状态
async function saveTimerState(state: TimerState) {
  try {
    await AsyncStorage.setItem('timerState', JSON.stringify(state));
  } catch (error) {
    console.error('Failed to save timer state:', error);
  }
}

// 加载计时器状态
async function loadTimerState(): Promise<TimerState | null> {
  try {
    const stateStr = await AsyncStorage.getItem('timerState');
    if (stateStr) {
      return JSON.parse(stateStr);
    }
  } catch (error) {
    console.error('Failed to load timer state:', error);
  }
  return null;
}

// 启动前台服务
async function startForegroundService(taskTitle: string, initialTime: number = 0) {
  if (Platform.OS === 'android') {
    await notifee.registerForegroundService(() => {
      return new Promise(() => {
        if (intervalId) {
          clearInterval(intervalId);
        }
        
        accumulatedTime = initialTime;
        startTime = Date.now();
        
        intervalId = setInterval(async () => {
          if (startTime === null) return;
          
          const now = Date.now();
          const elapsedSeconds = Math.floor((now - startTime) / 1000);
          const totalSeconds = accumulatedTime + elapsedSeconds;
          
          await updateNotification(taskTitle, totalSeconds);
          
          // 保存当前状态
          await saveTimerState({
            isRunning: true,
            startTime,
            accumulatedTime,
            taskTitle
          });
        }, 1000);
      });
    });
  }
}

// 停止前台服务
async function stopForegroundService() {
  if (Platform.OS === 'android') {
    if (intervalId) {
      clearInterval(intervalId);
      intervalId = null;
    }
    if (startTime !== null) {
      const now = Date.now();
      accumulatedTime += Math.floor((now - startTime) / 1000);
      startTime = null;
    }
    await notifee.stopForegroundService();
  }
}

// 注册事件监听
notifee.onBackgroundEvent(async ({ type, detail }) => {
  if (type === EventType.ACTION_PRESS && detail.pressAction?.id === 'stop') {
    await stopTimerService();
  }
});

notifee.onForegroundEvent(async ({ type, detail }) => {
  if (type === EventType.ACTION_PRESS && detail.pressAction?.id === 'stop') {
    await stopTimerService();
  }
});

// 注册后台任务
export async function registerBackgroundTask() {
  try {
    await createNotificationChannel();
    // 恢复之前的计时状态
    const savedState = await loadTimerState();
    if (savedState?.isRunning) {
      await startTimerService(savedState.taskTitle, savedState.accumulatedTime);
    }
  } catch (error) {
    console.error('Failed to register background task:', error);
  }
}

// 启动计时器服务
export async function startTimerService(taskTitle: string, initialTime: number = 0) {
  try {
    accumulatedTime = initialTime;
    await startForegroundService(taskTitle, initialTime);
  } catch (error) {
    console.error('Failed to start timer service:', error);
  }
}

// 暂停计时器服务
export async function pauseTimerService() {
  try {
    if (startTime !== null) {
      const now = Date.now();
      accumulatedTime += Math.floor((now - startTime) / 1000);
      startTime = null;
    }
    if (intervalId) {
      clearInterval(intervalId);
      intervalId = null;
    }
    await saveTimerState({
      isRunning: false,
      startTime: null,
      accumulatedTime,
      taskTitle: ''
    });
  } catch (error) {
    console.error('Failed to pause timer service:', error);
  }
}

// 停止计时器服务
export async function stopTimerService() {
  try {
    await stopForegroundService();
    await AsyncStorage.removeItem('timerState');
    await notifee.cancelAllNotifications();
    startTime = null;
    accumulatedTime = 0;
  } catch (error) {
    console.error('Failed to stop timer service:', error);
  }
}

// 获取当前累计时间（秒）
export async function getCurrentTime(): Promise<number> {
  if (startTime === null) {
    return accumulatedTime;
  }
  const now = Date.now();
  return accumulatedTime + Math.floor((now - startTime) / 1000);
} 